package net.jxtz.jxtzos.landtax;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.landtax.Residential;
import net.jxtz.jxtzos.service.landtax.ResidentialService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author a123
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener<Residential> {

    private static final int BATCH_COUNT = 500;

    private final List<Residential> list = new ArrayList<>();

    private final ResidentialService residentialService;

    public ExcelListener(ResidentialService residentialService){
        this.residentialService = residentialService;
    }

    /**
     * 每解析到一条数据回调的方法
     * @param data 对象
     * @param context 数据
     */
    @Override
    public void invoke(Residential data, AnalysisContext context) {
        log.info("解析到一条数据 --> " + data.toString());
        list.add(data);
        if (list.size() >= BATCH_COUNT){
            residentialService.saveBatch(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        residentialService.saveBatch(list);
        log.info("所有数据解析完毕！");
    }
}
